package edu.biwu.response;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/resp/demo05")
public class ResponseDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取字节输出流，并且应用缓冲流
        ServletOutputStream os = response.getOutputStream();
        BufferedOutputStream bs = new BufferedOutputStream(os);

        //2.如何告诉浏览器，我要响应给你的内容是一张图片
        String mimeType = getServletContext().getMimeType("1.jpg");
        System.out.println(mimeType);

        //3.设置响应头，目的就是告诉浏览器我即将响应给你的内容类型
        response.setHeader("Content-Type",mimeType);

        //4.将文件的字节流数据响应给浏览器（利用输入流获取1.jpg的字节，然后再利用输出流写给浏览器）
        InputStream is = getServletContext().getResourceAsStream("/1.jpg");
        BufferedInputStream bis = new BufferedInputStream(is);
        int b;
        while ((b = bis.read()) != -1){
            bs.write(b);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
